package forum.dao.file;

import forum.entities.Topic;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.math.BigInteger;

public class FileTopicDAO extends FileGenericDAO<Topic> {


    public FileTopicDAO() {
        super("src\\main\\resources\\topics.xml","topics","topic");
    }

    @Override
    protected Element mapEntityToElement(Document document, Element element, Topic topic) {
        Element topicNode = document.createElement("topic");
        element.appendChild(topicNode);

        Node idNode = document.createElement("id");
        idNode.setTextContent(topic.getId().toString());
        topicNode.appendChild(idNode);

        Node topicNameNode = document.createElement("topicName");
        topicNameNode.setTextContent(topic.getTopicName());
        topicNode.appendChild(topicNameNode);

        Node parentCategoryIdNode = document.createElement("parentCategoryName");
        parentCategoryIdNode.setTextContent(topic.getParentCategoryId().toString());
        topicNode.appendChild(parentCategoryIdNode);

        Node authorIdNode = document.createElement("authorId");
        authorIdNode.setTextContent(topic.getAuthorId().toString());
        topicNode.appendChild(authorIdNode);

        return topicNode;
    }


    @Override
    protected Topic mapElementToEntity(Document document, Element topicNode) {
        NodeList childNodes = topicNode.getChildNodes();
        Topic topic = new Topic(new BigInteger(childNodes.item(0).getTextContent()));
        topic.setTopicName(childNodes.item(1).getTextContent());
        topic.setParentCategoryId(new BigInteger(childNodes.item(2).getTextContent()));
        topic.setAuthorId(new BigInteger(childNodes.item(3).getTextContent()));
        return topic;
    }

    @Override
    protected Topic newEntity() {
        return new Topic(getNewKey());
    }
}
